// 数据上传页面
import React, { useState, useEffect } from 'react';
import { Layout, Card, Upload, Button, Form, Input, Table, message, Divider, Space, Typography, Tabs, Modal, Tag, Progress } from 'antd';
import { UploadOutlined, PlusOutlined, EyeOutlined, LineChartOutlined, ReloadOutlined, DownloadOutlined } from '@ant-design/icons';
import { isValidCSV, formatFileSize } from '../utils/fileUtils';
import { mockService } from '../services/mockService';
import type { Column, Dataset } from '../types';

const { Content } = Layout;
const { Title, Text } = Typography;

// 定义上传任务类型
interface UploadTask {
  id: string;
  name: string;
  fileName: string;
  status: 'running' | 'completed' | 'failed' | 'pending';
  progress: number;
  fileSize: number;
  createTime: string;
  completeTime?: string;
  errorMessage?: string;
}

const UploadPage: React.FC = () => {
  const [form] = Form.useForm();
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('1');
  const [uploadTasks, setUploadTasks] = useState<UploadTask[]>([]);
  const [createTaskModalVisible, setCreateTaskModalVisible] = useState(false);
  const [datasets, setDatasets] = useState<Dataset[]>([]);
  // 预览数据状态
  const [previewDataset, setPreviewDataset] = useState<Dataset | null>(null);
  const [previewData, setPreviewData] = useState<any[]>([]);
  const [previewColumns, setPreviewColumns] = useState<any[]>([]);
  const [previewPagination, setPreviewPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  
  // 分析任务相关状态
  interface AnalysisTask {
    datasetId: string;
    status: 'pending' | 'running' | 'completed' | 'failed';
    progress: number;
    result?: DataQualityResult;
  }
  
  interface DataQualityResult {
    missingValues: { [key: string]: number };
    duplicateRows: number;
    outliers: { [key: string]: number };
    dataTypes: { [key: string]: string };
    summary: {
      completeness: number;
      uniqueness: number;
      consistency: number;
      overallQuality: number;
    };
  }
  
  const [analysisTasks, setAnalysisTasks] = useState<AnalysisTask[]>([]);
  const [currentAnalysisResult, setCurrentAnalysisResult] = useState<DataQualityResult | null>(null);
  const [analyzedDataset, setAnalyzedDataset] = useState<Dataset | null>(null);

  // 初始化上传任务列表
  useEffect(() => {
    // 模拟获取上传任务数据
    const mockTasks: UploadTask[] = [
      {
        id: '1',
        name: '用户行为数据集',
        fileName: 'user_behavior.csv',
        status: 'completed',
        progress: 100,
        fileSize: 2097152,
        createTime: '2024-01-15 10:30:00',
        completeTime: '2024-01-15 10:32:45'
      },
      {
        id: '2',
        name: '销售记录',
        fileName: 'sales_data.csv',
        status: 'running',
        progress: 65,
        fileSize: 5242880,
        createTime: '2024-01-15 14:20:00'
      },
      {
        id: '3',
        name: '产品信息',
        fileName: 'products.csv',
        status: 'failed',
        progress: 0,
        fileSize: 524288,
        createTime: '2024-01-14 16:45:00',
        errorMessage: '文件格式不正确'
      },
      {
        id: '4',
        name: '客户反馈',
        fileName: 'customer_feedback.csv',
        status: 'completed',
        progress: 100,
        fileSize: 1048576,
        createTime: '2024-01-14 09:15:00',
        completeTime: '2024-01-14 09:16:30'
      }
    ];
    setUploadTasks(mockTasks);
    
    // 模拟获取数据集列表
    const loadDatasets = async () => {
      try {
        const { data } = await mockService.datasets.getAll();
        if (data && data.length > 0) {
          // 如果API返回了数据，使用API数据
          setDatasets(data);
        } else {
          // 否则使用模拟数据（包含schema信息）
          const mockDatasetsWithSchema: Dataset[] = [
            {
              id: '1',
              name: '用户行为数据集',
              description: '用户在平台上的行为记录数据',
              uploadedAt: '2024-01-15 10:30:00',
              fileSize: 1024 * 1024 * 2.5, // 2.5MB
              rows: 5000,
              columns: [
                { name: 'user_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'action', type: 'string', isSelected: true, isTarget: false },
                { name: 'timestamp', type: 'datetime', isSelected: true, isTarget: false },
                { name: 'product_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'session_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'duration', type: 'number', isSelected: true, isTarget: false },
                { name: 'device', type: 'string', isSelected: true, isTarget: false },
                { name: 'browser', type: 'string', isSelected: true, isTarget: false },
              ]
            },
            {
              id: '2',
              name: '产品销售数据',
              description: '产品销售记录和统计数据',
              uploadedAt: '2024-01-14 14:20:00',
              fileSize: 1024 * 1024 * 5.2, // 5.2MB
              rows: 12000,
              columns: [
                { name: 'order_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'product_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'product_name', type: 'string', isSelected: true, isTarget: false },
                { name: 'category', type: 'string', isSelected: true, isTarget: false },
                { name: 'quantity', type: 'number', isSelected: true, isTarget: false },
                { name: 'price', type: 'number', isSelected: true, isTarget: false },
                { name: 'total_amount', type: 'number', isSelected: true, isTarget: false },
                { name: 'order_date', type: 'date', isSelected: true, isTarget: false },
                { name: 'customer_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'region', type: 'string', isSelected: true, isTarget: false },
              ]
            },
            {
              id: '3',
              name: '客户反馈数据',
              description: '客户对产品的评价和反馈',
              uploadedAt: '2024-01-13 09:15:00',
              fileSize: 1024 * 512, // 512KB
              rows: 3500,
              columns: [
                { name: 'feedback_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'customer_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'product_id', type: 'string', isSelected: true, isTarget: false },
                { name: 'rating', type: 'number', isSelected: true, isTarget: true },
                { name: 'feedback_text', type: 'string', isSelected: true, isTarget: false },
                { name: 'feedback_date', type: 'datetime', isSelected: true, isTarget: false },
                { name: 'is_resolved', type: 'boolean', isSelected: true, isTarget: false },
                { name: 'priority', type: 'string', isSelected: true, isTarget: false },
              ]
            },
          ];
          setDatasets(mockDatasetsWithSchema);
        }
      } catch (error) {
        console.error('获取数据集列表失败:', error);
      }
    };
    loadDatasets();
    

  }, []);

  // 处理数据集名称点击事件
  const handleDatasetNameClick = (dataset: Dataset) => {
    console.log('点击数据集:', dataset.name);
    // 切换到数据浏览标签页
    setActiveTab('2');
    // 设置预览数据集
    setPreviewDataset(dataset);
    
    // 生成表格列配置
    const columns = dataset.columns.map((field: Column) => ({
      title: field.name,
      dataIndex: field.name,
      key: field.name,
      ellipsis: true,
      width: 150
    }));
    setPreviewColumns(columns);
    
    // 生成预览数据
    const { data, total } = generatePreviewData(dataset, 1, 10);
    setPreviewData(data);
    setPreviewPagination({
      current: 1,
      pageSize: 10,
      total: total
    });
    
    console.log('已切换到数据浏览标签页，预览数据集:', dataset.name);
  };

  // 生成模拟预览数据
  const generatePreviewData = (dataset: Dataset, page: number, pageSize: number) => {
    // 使用数据集的columns字段
    const fields = dataset.columns || [
      { name: 'id', type: 'string', isSelected: true, isTarget: false },
      { name: 'field1', type: 'string', isSelected: true, isTarget: false },
      { name: 'field2', type: 'number', isSelected: true, isTarget: false },
      { name: 'field3', type: 'date', isSelected: true, isTarget: false },
      { name: 'field4', type: 'boolean', isSelected: true, isTarget: false },
    ];
    
    const totalData = dataset.rows || 100; // 使用数据集的rows字段或默认100条
    const startIndex = (page - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, totalData);
    
    // 根据字段信息生成模拟数据
    const data = [];
    for (let i = startIndex; i < endIndex; i++) {
      const row: any = {};
      fields.forEach((field: Column) => {
        switch (field.type) {
          case 'string':
            row[field.name] = `${field.name}_${i + 1}`;
            break;
          case 'number':
            row[field.name] = Math.floor(Math.random() * 1000);
            break;
          case 'boolean':
            row[field.name] = Math.random() > 0.5;
            break;
          case 'date':
            const date = new Date();
            date.setDate(date.getDate() - Math.floor(Math.random() * 30));
            row[field.name] = date.toISOString().split('T')[0];
            break;
          case 'datetime':
            const datetime = new Date();
            datetime.setDate(datetime.getDate() - Math.floor(Math.random() * 30));
            row[field.name] = datetime.toLocaleString('zh-CN');
            break;
          default:
            row[field.name] = `${field.name}_${i + 1}`;
        }
      });
      data.push(row);
    }
    
    return { data, total: totalData };
  };

  // 处理预览按钮点击
  const handlePreviewDataset = (dataset: Dataset) => {
    setPreviewDataset(dataset);
    
    // 生成表格列配置
    const columns = dataset.columns.map((field: Column) => ({
      title: field.name, // 使用字段名作为标题
      dataIndex: field.name,
      key: field.name,
      ellipsis: true,
      width: 150
    }));
    setPreviewColumns(columns);
    
    // 初始加载第一页数据
    const { data, total } = generatePreviewData(dataset, 1, 10);
    setPreviewData(data);
    setPreviewPagination(prev => ({ ...prev, current: 1, total }));
  };

  // 处理预览数据分页
  const handlePreviewPageChange = (page: number, pageSize: number) => {
    if (previewDataset) {
      const { data } = generatePreviewData(previewDataset, page, pageSize);
      setPreviewData(data);
      setPreviewPagination(prev => ({ ...prev, current: page, pageSize }));
    }
  };

  // 创建新的上传任务
  const handleCreateTask = () => {
    setCreateTaskModalVisible(true);
    form.resetFields();
    setUploadedFile(null);
  };
  
  // 开始新任务上传
  const handleStartTask = async (values: any) => {
    if (!uploadedFile) {
      message.error('请先上传CSV文件');
      return;
    }

    try {
      setLoading(true);
      
      // 创建新的上传任务记录
      const newTask: UploadTask = {
        id: Date.now().toString(),
        name: values.name,
        fileName: uploadedFile.name,
        status: 'pending',
        progress: 0,
        fileSize: uploadedFile.size,
        createTime: new Date().toLocaleString('zh-CN')
      };
      
      setUploadTasks([newTask, ...uploadTasks]);
      setCreateTaskModalVisible(false);
      form.resetFields();
      setUploadedFile(null);
      setLoading(false); // 重置loading状态
      
      // 开始模拟上传进度
      setTimeout(() => {
        simulateUploadProgress(newTask.id, uploadedFile, values.name, values.description);
      }, 500);
    } catch (error) {
      message.error('创建任务失败');
      setLoading(false);
    }
  };
  
  // 模拟上传进度
  const simulateUploadProgress = async (taskId: string, file: File, datasetName: string, description?: string) => {
    // 更新任务状态为运行中
    setUploadTasks(prev => prev.map(task => 
      task.id === taskId ? {
        ...task,
        status: 'running',
        progress: 0
      } : task
    ));

    let progress = 0;
    const interval = setInterval(() => {
      progress += Math.random() * 20;
      if (progress >= 100) {
        progress = 100;
        clearInterval(interval);
        
        // 实际上传数据集
        mockService.datasets.upload(file, datasetName, description || '')
          .then((response) => {
            if (response.success) {
              setUploadTasks(prev => prev.map(task => 
                task.id === taskId ? {
                  ...task,
                  status: 'completed',
                  progress: 100,
                  completeTime: new Date().toLocaleString('zh-CN')
                } : task
              ));
              message.success('数据集上传成功！');
              
              // 更新数据集列表
              mockService.datasets.getAll().then(({ data }) => {
                if (data) {
                  setDatasets(data);
                }
              });
            } else {
              setUploadTasks(prev => prev.map(task => 
                task.id === taskId ? {
                  ...task,
                  status: 'failed',
                  progress: 0,
                  errorMessage: response.error || '上传失败'
                } : task
              ));
              message.error(response.error || '上传失败');
            }
          })
          .catch((error) => {
            setUploadTasks(prev => prev.map(task => 
              task.id === taskId ? {
                ...task,
                status: 'failed',
                progress: 0,
                errorMessage: '上传失败'
              } : task
            ));
            message.error('上传失败，请重试');
            console.error('上传错误:', error);
          });
      } else {
        setUploadTasks(prev => prev.map(task => 
          task.id === taskId ? {
            ...task,
            status: 'running',
            progress: Math.min(progress, 99)
          } : task
        ));
      }
    }, 500);
  };
  
  // 重试失败的任务（由于没有原始文件，重试功能暂时禁用，提示用户重新创建任务）
  const handleRetryTask = () => {
    message.warning('重试功能需要原始文件，请重新创建数据集任务');
    // 如果需要实现重试，需要保存原始文件或文件路径
  };
  
  // 删除任务
  const handleDeleteTask = (taskId: string) => {
    setUploadTasks(prev => prev.filter(task => task.id !== taskId));
    message.success('任务已删除');
  };

  // 刷新任务列表
  const handleRefreshTasks = () => {
    message.success('任务列表已刷新');
    // 在实际应用中，这里应该重新从服务器获取最新的任务列表
  };
  
  // 上传任务列表的列配置
  const taskColumns = [
    {
      title: '数据集名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
      render: (text: string, record: UploadTask) => {
        if (record.status === 'completed') {
          return (
            <Button 
              type="link" 
              onClick={() => {
                // 查找对应的数据集
                mockService.datasets.getAll().then(({ data }) => {
                  if (data) {
                    const dataset = data.find(d => d.name === record.name);
                    if (dataset) {
                      handleDatasetClick(dataset);
                    }
                  }
                });
              }} 
              style={{ padding: 0, height: 'auto' }}
            >
              {text}
            </Button>
          );
        }
        return text;
      },
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
      width: 150,
      ellipsis: true,
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 100,
      render: (size: number) => formatFileSize(size),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        let color = '';
        let text = '';
        
        switch (status) {
          case 'running':
            color = 'blue';
            text = '上传中';
            break;
          case 'completed':
            color = 'green';
            text = '已完成';
            break;
          case 'failed':
            color = 'red';
            text = '失败';
            break;
          case 'pending':
            color = 'orange';
            text = '等待中';
            break;
          default:
            color = 'default';
            text = status;
        }
        
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      width: 150,
      render: (progress: number, record: UploadTask) => (
        <Progress 
          percent={progress} 
          showInfo 
          status={record.status === 'failed' ? 'exception' : (progress === 100 ? 'success' : 'active')} 
          size="small"
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '完成时间',
      dataIndex: 'completeTime',
      key: 'completeTime',
      width: 150,
      render: (time: string) => time || '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: UploadTask) => (
        <Space size="middle">
          {record.status === 'completed' && (
            <Button type="link" icon={<DownloadOutlined />}>下载</Button>
          )}
          {record.status === 'failed' && (
            <Button type="link" icon={<ReloadOutlined />} onClick={handleRetryTask}>重试</Button>
          )}
          <Button type="link" danger onClick={() => handleDeleteTask(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];


  // 处理数据集点击跳转
  const handleDatasetClick = (dataset: Dataset) => {
    // 切换到数据浏览页签
    setActiveTab('2');
    // 设置要预览的数据集
    setPreviewDataset(dataset);
    
    // 生成预览数据
    const columns = dataset.columns.map((field: Column) => ({
      title: field.name,
      dataIndex: field.name,
      key: field.name,
      ellipsis: true,
      width: 150
    }));
    setPreviewColumns(columns);
    
    const { data, total } = generatePreviewData(dataset, 1, 10);
    setPreviewData(data);
    setPreviewPagination(prev => ({ ...prev, current: 1, total }));
  };

  // 数据上传标签页内容
  const renderUploadTab = () => (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <Title level={4} style={{ margin: 0 }}>数据集</Title>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateTask}>
          创建数据集
        </Button>
      </div>
      <Text type="secondary">支持CSV格式文件上传，用于后续特征工程和模型训练</Text>
      
      <Divider />
      
      {/* 上传任务列表 */}
      <div style={{ marginTop: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
          <Title level={4} style={{ margin: 0 }}>数据集列表</Title>
          <Button icon={<ReloadOutlined />} onClick={handleRefreshTasks}>刷新</Button>
        </div>
        <Table 
          dataSource={uploadTasks} 
          columns={taskColumns} 
          rowKey="id" 
          pagination={{ pageSize: 10 }}
          onRow={(record) => ({
            style: { cursor: record.status === 'completed' ? 'pointer' : 'default' },
            onClick: () => {
              if (record.status === 'completed') {
                // 查找对应的数据集
                mockService.datasets.getAll().then(({ data }) => {
                  if (data) {
                    const dataset = data.find(d => d.name === record.name);
                    if (dataset) {
                      handleDatasetClick(dataset);
                    }
                  }
                });
              }
            },
          })}
        />
      </div>
    </Card>
  );
  
  // 处理数据集分析
  const handleAnalyzeDataset = (dataset: Dataset) => {
    // 重置当前分析结果
    setCurrentAnalysisResult(null);
    setAnalyzedDataset(dataset);
    
    // 创建新的分析任务
    const newTask: AnalysisTask = {
      datasetId: dataset.id,
      status: 'pending',
      progress: 0
    };
    
    setAnalysisTasks(prev => [...prev.filter(t => t.datasetId !== dataset.id), newTask]);
    
    // 模拟分析过程
    setTimeout(() => {
      // 更新为运行状态
      setAnalysisTasks(prev => prev.map(task => 
        task.datasetId === dataset.id ? { ...task, status: 'running' } : task
      ));
      
      // 模拟进度更新
      let progress = 0;
      const interval = setInterval(() => {
        progress += 10;
        setAnalysisTasks(prev => prev.map(task => 
          task.datasetId === dataset.id ? { ...task, progress } : task
        ));
        
        if (progress >= 100) {
          clearInterval(interval);
          
          // 生成模拟分析结果
          const mockResult: DataQualityResult = {
            missingValues: dataset.columns.reduce((acc, col) => {
              acc[col.name] = Math.floor(Math.random() * 5); // 0-4个缺失值
              return acc;
            }, {} as { [key: string]: number }),
            duplicateRows: Math.floor(Math.random() * 10), // 0-9个重复行
            outliers: dataset.columns.filter(col => col.type === 'number').reduce((acc, col) => {
              acc[col.name] = Math.floor(Math.random() * 3); // 0-2个异常值
              return acc;
            }, {} as { [key: string]: number }),
            dataTypes: dataset.columns.reduce((acc, col) => {
              acc[col.name] = col.type;
              return acc;
            }, {} as { [key: string]: string }),
            summary: {
              completeness: 95 + Math.random() * 5, // 95-100%
              uniqueness: 98 + Math.random() * 2, // 98-100%
              consistency: 92 + Math.random() * 8, // 92-100%
              overallQuality: 94 + Math.random() * 6 // 94-100%
            }
          };
          
          // 完成分析
          setAnalysisTasks(prev => prev.map(task => 
            task.datasetId === dataset.id 
              ? { ...task, status: 'completed', progress: 100, result: mockResult }
              : task
          ));
          
          // 更新当前分析结果
          setCurrentAnalysisResult(mockResult);
        }
      }, 500);
    }, 100);
  };
  
  // 获取分析任务状态显示
  const getTaskStatusDisplay = (task?: AnalysisTask) => {
    if (!task) return null;
    
    switch (task.status) {
      case 'pending':
        return <Tag color="default">等待中</Tag>;
      case 'running':
        return (
          <div>
            <Tag color="processing">分析中</Tag>
            <Progress 
              percent={task.progress} 
              status="active" 
              strokeColor={{ from: '#108ee9', to: '#87d068' }}
              style={{ marginTop: 8 }}
              size="small"
            />
          </div>
        );
      case 'completed':
        return <Tag color="success">已完成</Tag>;
      case 'failed':
        return <Tag color="error">分析失败</Tag>;
      default:
        return null;
    }
  };
  
  // 渲染数据质量分析结果
  const renderDataQualityAnalysis = () => {
    if (!currentAnalysisResult || !analyzedDataset) return null;
    
    const result = currentAnalysisResult;
    
    return (
      <Card title={`${analyzedDataset.name} - 数据质量分析结果`} style={{ marginTop: 24 }}>
        <Title level={5}>总体质量评分</Title>
        <div style={{ display: 'flex', gap: '16px', marginBottom: '24px' }}>
          <Card size="small" style={{ flex: 1 }}>
            <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>完整性</p>
            <p style={{ margin: '8px 0 0 0', fontSize: '24px', fontWeight: 'bold', color: result.summary.completeness > 95 ? '#52c41a' : '#faad14' }}>
              {result.summary.completeness.toFixed(1)}%
            </p>
          </Card>
          <Card size="small" style={{ flex: 1 }}>
            <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>唯一性</p>
            <p style={{ margin: '8px 0 0 0', fontSize: '24px', fontWeight: 'bold', color: result.summary.uniqueness > 95 ? '#52c41a' : '#faad14' }}>
              {result.summary.uniqueness.toFixed(1)}%
            </p>
          </Card>
          <Card size="small" style={{ flex: 1 }}>
            <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>一致性</p>
            <p style={{ margin: '8px 0 0 0', fontSize: '24px', fontWeight: 'bold', color: result.summary.consistency > 90 ? '#52c41a' : '#faad14' }}>
              {result.summary.consistency.toFixed(1)}%
            </p>
          </Card>
          <Card size="small" style={{ flex: 1 }}>
            <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>总体质量</p>
            <p style={{ margin: '8px 0 0 0', fontSize: '24px', fontWeight: 'bold', color: result.summary.overallQuality > 95 ? '#52c41a' : '#faad14' }}>
              {result.summary.overallQuality.toFixed(1)}%
            </p>
          </Card>
        </div>
        
        <Divider />
        
        <Title level={5}>数据问题检测</Title>
        <div style={{ marginBottom: '24px' }}>
          <p><strong>缺失值统计：</strong></p>
          <ul>
            {Object.entries(result.missingValues).map(([col, count]) => (
              <li key={col}>
                {col}: {count} 个缺失值 {count > 0 && <Tag color="warning">需要处理</Tag>}
              </li>
            ))}
          </ul>
          
          <p style={{ marginTop: '16px' }}><strong>重复行：</strong> {result.duplicateRows} 行 {result.duplicateRows > 0 && <Tag color="warning">需要处理</Tag>}</p>
          
          {Object.keys(result.outliers).length > 0 && (
            <>
              <p style={{ marginTop: '16px' }}><strong>异常值检测：</strong></p>
              <ul>
                {Object.entries(result.outliers).map(([col, count]) => (
                  <li key={col}>
                    {col}: {count} 个异常值 {count > 0 && <Tag color="warning">需要处理</Tag>}
                  </li>
                ))}
              </ul>
            </>
          )}
        </div>
        
        <Divider />
        
        <Title level={5}>数据类型检查</Title>
        <Table
          dataSource={Object.entries(result.dataTypes).map(([name, type]) => ({ name, type }))}
          columns={[
            { title: '字段名', dataIndex: 'name', key: 'name' },
            { title: '数据类型', dataIndex: 'type', key: 'type' }
          ]}
          pagination={false}
          size="small"
        />
      </Card>
    );
  };
  
  // 数据浏览标签页内容
    const renderBrowseTab = () => (
      <Card>
        <Title level={4}>数据浏览</Title>
        <Text type="secondary">查看已上传的数据集</Text>
        
        <Divider />
        
        <Table 
          dataSource={datasets} 
          columns={[
            {
              title: '数据集名称',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '上传时间',
              dataIndex: 'uploadedAt',
              key: 'uploadedAt',
            },
            {
              title: '文件大小',
              dataIndex: 'fileSize',
              key: 'fileSize',
              render: (size: number) => formatFileSize(size),
            },
            {
              title: '记录数',
              dataIndex: 'rows',
              key: 'rows',
            },
            {
              title: '操作',
              key: 'action',
              render: (_, record: Dataset) => (
                <Space size="middle">
                  <Button type="link" icon={<EyeOutlined />} onClick={() => handlePreviewDataset(record)}>预览</Button>
                  <Button type="link" icon={<DownloadOutlined />}>下载</Button>
                  <Button type="link" danger>删除</Button>
                </Space>
              ),
            },
          ]} 
          rowKey="id" 
          pagination={{ pageSize: 5 }}
        />
        
        {/* 数据集预览表格 */}
        {previewDataset && (
          <div style={{ marginTop: '24px' }}>
            <Card title={`${previewDataset.name} - 数据预览`}>
              <Table
                    dataSource={previewData}
                    columns={previewColumns}
                    rowKey={(_, index) => String(index)}
                    pagination={{
                      current: previewPagination.current,
                      pageSize: previewPagination.pageSize,
                      total: previewPagination.total,
                      onChange: handlePreviewPageChange,
                      showSizeChanger: true,
                      showQuickJumper: true,
                      showTotal: (total) => `共 ${total} 条记录`
                    }}
                    size="small"
                    scroll={{ x: 'max-content' }}
                  />
            </Card>
          </div>
        )}
      </Card>
    );
  
  // 数据分析标签页内容
    const renderAnalysisTab = () => (
      <Card>
        <Title level={4}>数据分析</Title>
        <Text type="secondary">对数据集进行质量分析和统计</Text>
        
        <Divider />
        
        <Title level={5}>数据集列表</Title>
        <Table 
          dataSource={datasets} 
          columns={[
            {
              title: '数据集名称',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '上传时间',
              dataIndex: 'uploadedAt',
              key: 'uploadedAt',
            },
            {
              title: '记录数',
              dataIndex: 'rows',
              key: 'rows',
            },
            {
              title: '分析状态',
              key: 'analysisStatus',
              render: (_, record: Dataset) => {
                const task = analysisTasks.find(t => t.datasetId === record.id);
                return getTaskStatusDisplay(task);
              },
            },
            {
              title: '操作',
              key: 'action',
              render: (_, record: Dataset) => {
                const task = analysisTasks.find(t => t.datasetId === record.id);
                const isAnalyzing = task?.status === 'running' || task?.status === 'pending';
                
                return (
                  <Space size="middle">
                    <Button 
                      type="primary" 
                      icon={<LineChartOutlined />} 
                      onClick={() => handleAnalyzeDataset(record)}
                      disabled={isAnalyzing}
                    >
                      分析
                    </Button>
                  </Space>
                );
              },
            },
          ]} 
          rowKey="id" 
          pagination={{ pageSize: 5 }}
        />
        
        {/* 数据分析结果 */}
        {renderDataQualityAnalysis()}
      </Card>
    );

  return (
    <Layout className="layout">
      <Content style={{ padding: '24px', minHeight: 'calc(100vh - 64px)' }}>
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          items={[
            {
              key: '1',
              label: <span><UploadOutlined /> 数据集</span>,
              children: renderUploadTab()
            },
            {
              key: '2',
              label: <span><EyeOutlined /> 数据浏览</span>,
              children: renderBrowseTab()
            },
            {
              key: '3',
              label: <span><LineChartOutlined /> 数据分析</span>,
              children: renderAnalysisTab()
            }
          ]}
        />
        
        {/* 创建数据集模态框 */}
        <Modal
          title="创建数据集"
          open={createTaskModalVisible}
          onCancel={() => {
            setCreateTaskModalVisible(false);
            form.resetFields();
            setUploadedFile(null);
          }}
          footer={null}
          width={600}
          destroyOnClose={true}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleStartTask}
          >
            <Form.Item 
              name="name" 
              label="数据集名称" 
              rules={[{ required: true, message: '请输入数据集名称' }]}
            >
              <Input placeholder="请输入数据集名称" />
            </Form.Item>

            <Form.Item 
              name="description" 
              label="数据集描述"
            >
              <Input.TextArea rows={3} placeholder="请输入数据集描述（可选）" />
            </Form.Item>

            <Form.Item
              name="file"
              label="CSV文件"
              rules={[{ required: true, message: '请上传CSV文件' }]}
            >
              <Upload
                name="file"
                multiple={false}
                beforeUpload={(file) => {
                  if (!isValidCSV(file)) {
                    message.error(`${file.name} 不是有效的CSV文件!`);
                    return Upload.LIST_IGNORE;
                  }
                  setUploadedFile(file);
                  return false; // 阻止自动上传
                }}
                onRemove={() => {
                  setUploadedFile(null);
                }}
                maxCount={1}
                accept=".csv"
                showUploadList={true}
                fileList={uploadedFile ? [{
                  uid: '1',
                  name: uploadedFile.name,
                  status: 'done',
                }] : []}
              >
                <Button icon={<UploadOutlined />}>选择CSV文件</Button>
              </Upload>
              {uploadedFile && (
                <Text type="secondary" style={{ display: 'block', marginTop: 8 }}>
                  已选择: {uploadedFile.name} ({formatFileSize(uploadedFile.size)})
                </Text>
              )}
            </Form.Item>
            
            <Form.Item>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  disabled={!uploadedFile}
                >
                  确定
                </Button>
                <Button 
                  onClick={() => {
                    setCreateTaskModalVisible(false);
                    form.resetFields();
                    setUploadedFile(null);
                  }}
                >
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Content>
    </Layout>
  );
};

export default UploadPage;